import {DO_SEARCH, RESET_SEARCH, SAVE_SEARCH_KEYWORD, CLEAR_SEARCH_HISTORY} from '../../config/ActionType'
import {fetch, API_DO_SEARCH} from '../../config/Api'

export const getSearchList = list => ({
  type: DO_SEARCH,
  payload: {list}
})

export const resetSearch = () => ({type: RESET_SEARCH})

export const saveSearchKeyword = keyword => ({
  type: SAVE_SEARCH_KEYWORD,
  payload: {keyword}
})

export const clearSearchHistory = () => ({type: CLEAR_SEARCH_HISTORY})

export function fetchSearchList(params) {
  return (dispatch, getState) => fetch(API_DO_SEARCH, params)(dispatch, getState)
    .then(json => {
      const list = json.data

      if (list && list.length) {
        dispatch(saveSearchKeyword(params.keyword))
      }

      return dispatch(getSearchList(list))
    })
}

export const actions = {
  getSearchList,
  resetSearch,
  fetchSearchList,
  clearSearchHistory
}

export const ACTION_HANDLERS = {
  [DO_SEARCH]: (state, action) => ({
    ...state,
    searchList: state.searchList.concat(action.payload.list),
    nextPage: state.nextPage + 1
  }),
  [RESET_SEARCH]: state => ({
    ...state,
    searchList: [],
    nextPage: 0
  }),
  [SAVE_SEARCH_KEYWORD]: (state, action) => {
    let keyword = action.payload.keyword,
      searchHistory = localStorage.getItem('csx-searchHistory')

    searchHistory = searchHistory ? searchHistory.split(',') : []

    searchHistory.map((item, i) => {
      if (item === keyword) {
        searchHistory.splice(i, 1)
      }
    })

    searchHistory.unshift(keyword)

    if (searchHistory.length > 12) {
      searchHistory.pop()
    }

    localStorage.setItem('csx-searchHistory', searchHistory)

    return {...state, searchHistory}
  },
  [CLEAR_SEARCH_HISTORY]: (state, action) => {
    localStorage.setItem('csx-searchHistory', [])

    return {...state, searchHistory: []}
  }
}

const searchHistory = localStorage.getItem('csx-searchHistory')

const initialState = {
  searchList: [],
  searchHistory: searchHistory ? searchHistory.split(',') : [],
  nextPage: 0
}

export default function(state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type]

  return handler ? handler(state, action) : state
}
